import { to } from 'await-to-js';
import { setState, type ActionsCreator } from '@ac/store';
import type { LoginParams, UserActions, UserSlice } from './types';

import { loginApi } from '@/api/common';

export const createUserActions: ActionsCreator<UserSlice, UserActions> = (set, get, api) => ({
	// 登录
	login: async (data: LoginParams) => {
		console.log('api', api.getInitialState());
		if (get().isLoading) return;

		set(state => {
			state.isLoading = true;
			state.error = null;
		});

		const [err, res] = await to(loginApi(data));

		if (res) {
			setState(set, { user: res, isLoading: false });
		} else {
			setState(set, { isLoading: false, error: err?.message });
		}
	}
});
